package com.yunji.hushuang.framework.web.servlet;

import com.yunji.hushuang.framework.web.annotation.HsRequestParam;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author hushuang
 * @since 2019/11/22
 */
public class HandlerMapping {

    private Pattern pattern;

    private Method method;

    private Object controller;

    private Map<String, Integer> paramIndexMapping;

    public HandlerMapping(Pattern pattern, Object controller, Method method) {
        this.pattern = pattern;
        this.method = method;
        this.controller = controller;
        this.paramIndexMapping = initParamIndexMapping(method);
    }

    public boolean isMatches(String url) {
        return pattern.matcher(url).matches();
    }

    public Object process(Object... args) throws Exception {
        return method.invoke(controller, args);
    }

    public Map<String, Integer> getParamIndexMapping() {
        return paramIndexMapping;
    }

    public int getParameterIndex(String key) {
        return paramIndexMapping.getOrDefault(key, -1);
    }

    public int getParameterCount() {
        return method.getParameterCount();
    }

    public Class<?> getParameterType(int index) {
        return method.getParameterTypes()[index];
    }

    private Map<String, Integer> initParamIndexMapping(Method method) {
        int count = method.getParameterCount();
        Map<String, Integer> map = new HashMap<>(count);

        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < count; i++) {
            HsRequestParam hsRequestParam = parameters[i].getAnnotation(HsRequestParam.class);
            if (hsRequestParam == null) {
                map.put(parameters[i].getType().getName(), i);
                continue;
            }
            if (hsRequestParam.value().trim().length() == 0) {
                throw new IllegalArgumentException("HsRequestParam could not be empty");
            }
            map.put(hsRequestParam.value(), i);
        }
        return map;
    }
}
